package GUILayer;

import ModelLayer.*;
import ModelLayer.Employee;
import ControlLayer.*;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import java.awt.Color;
import java.awt.Font;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingWorker;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.text.DateFormat;
import java.util.ArrayList;

import javax.swing.DefaultComboBoxModel;

public class MainWindow extends JFrame {

	private JPanel contentPane;

	private static MainWindow instance;

	private JTable tableInvoice;
	private JTable tableProduct;
	private JTable tableCustomer;
	private JTable tableDelivery;
	private JTable tableEmployee;
	private JTable tableArchiveContact;
	private JTable tableArchiveProduct;

	private JPanel panelProduct;
	private JPanel panelInvoice;
	private JPanel panelCustomer;
	private JPanel panelDelivery;
	private JPanel panelEmployee;
	private JPanel panelStats;
	private JPanel panelArchive;

	private InvoiceDetails detailsInvoice;
	private GUILayer.Product product;
	private GUILayer.CustomerDetails customerD;
	private GUILayer.NewCustomer customerN;
	private GUILayer.Delivery delivery;
	private GUILayer.Employee employee;
	private Invoice invoice;

	private IFSearch search;
	private IFCreate create;
	private IFUpdate update;

	private ArrayList<SalesOrder> salesOrders;
	private ArrayList<Contact> contacts;
	private ArrayList<ModelLayer.Delivery> deliveries;
	private ArrayList<ModelLayer.Employee> employees;
	private ArrayList<ModelLayer.Product> products;
	private ArrayList<Contact> archivedContacts;
	private ArrayList<ModelLayer.Product> archivedProducts;
	
	private LoadingWindow loadingWindow;
	private Statistics statistics;

	public static MainWindow getInstance() {
		if (instance == null) {
			instance = new MainWindow();
		}
		return instance;
	}

	/**
	 * Create the frame.
	 */
	private MainWindow() {

		search = new SearchControler();
		create = new CreateControler();
		update = new UpdateControler();

		panelInvoice = new JPanel();
		panelProduct = new JPanel();
		panelCustomer = new JPanel();
		panelDelivery = new JPanel();
		panelEmployee = new JPanel();
		panelStats = new JPanel();
		panelArchive = new JPanel();

		tableInvoice = new JTable();
		tableProduct = new JTable();
		tableCustomer = new JTable();
		tableDelivery = new JTable();
		tableEmployee = new JTable();
		tableArchiveContact = new JTable();
		tableArchiveProduct = new JTable();
		
		loadingWindow = new LoadingWindow();
		loadingWindow.showWindow();

		setResizable(false);
		setTitle("Gourmet Art");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBackground(new Color(255, 255, 204));
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblLogo = new JLabel("");
		lblLogo.setIcon(new ImageIcon("image/gourmetArtsmall.png"));
		lblLogo.setBounds(10, 11, 300, 60);
		contentPane.add(lblLogo);

		JButton btnInvoice = new JButton("Invoice");
		btnInvoice.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				panelInvoice.setVisible(true);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(false);
				panelStats.setVisible(false);
				panelArchive.setVisible(false);
			}
		});
		btnInvoice.setBounds(10, 75, 89, 60);
		contentPane.add(btnInvoice);
		
		JButton btnProduct = new JButton("Product");
		btnProduct.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (products == null) {
					products = search.getAllProducts();
				}
				setTableProduct(tableProduct, products);
				panelInvoice.setVisible(false);
				panelProduct.setVisible(true);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(false);
				panelStats.setVisible(false);
				panelArchive.setVisible(false);
			}
		});
		btnProduct.setBounds(10, 146, 89, 60);
		contentPane.add(btnProduct);
		
		JButton btnCustomer = new JButton("Clients");
		btnCustomer.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (contacts == null) {
					contacts = search.getAllCustomers();
				}
				setTableCustomer(tableCustomer, contacts);
				panelInvoice.setVisible(false);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(true);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(false);
				panelStats.setVisible(false);
				panelArchive.setVisible(false);
			}
		});
		btnCustomer.setBounds(10, 217, 89, 60);
		contentPane.add(btnCustomer);
		
		JButton btnDelivery = new JButton("Delivery");
		btnDelivery.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (deliveries == null) {
					deliveries = search.getAllDelivery();
				}
				setTableDelivery(tableDelivery, deliveries);
				panelInvoice.setVisible(false);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(true);
				panelEmployee.setVisible(false);
				panelStats.setVisible(false);
				panelArchive.setVisible(false);
			}
		});
		btnDelivery.setBounds(10, 288, 89, 60);
		contentPane.add(btnDelivery);
		
		JButton btnEmployee = new JButton("Employee");
		btnEmployee.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (employees == null) {
					employees = search.getAllEmployees();
				}
				setTableEmployee(tableEmployee, employees);
				panelInvoice.setVisible(false);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(true);
				panelStats.setVisible(false);
				panelArchive.setVisible(false);
			}
		});
		btnEmployee.setBounds(10, 359, 89, 60);
		contentPane.add(btnEmployee);
		
		JButton btnStatistics = new JButton("Statistics");
		btnStatistics.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				//loadingWindow.showWindow();
				
				statistics = new Statistics();
				statistics.execute();
				
				//loadingWindow.closeWindow();
				
				panelInvoice.setVisible(false);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(false);
				panelStats.setVisible(true);
				panelArchive.setVisible(false);
			}
		});
		btnStatistics.setBounds(10, 430, 89, 60);
		contentPane.add(btnStatistics);
		
		JButton btnArchive = new JButton("Archive");
		btnArchive.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				archivedContacts = search.getAllArchivedContacts();
				archivedProducts = search.getArchivedProducts();

				setTableArchiveContacts(tableArchiveContact, archivedContacts);
				setTableArchiveProducts(tableArchiveProduct, archivedProducts);

				panelInvoice.setVisible(false);
				panelProduct.setVisible(false);
				panelCustomer.setVisible(false);
				panelDelivery.setVisible(false);
				panelEmployee.setVisible(false);
				panelStats.setVisible(false);
				panelArchive.setVisible(true);
			}
		});
		btnArchive.setBounds(10, 500, 89, 60);
		contentPane.add(btnArchive);
		loadingWindow.setLoadingBarStatus(30);
		buildInvoice();
		loadingWindow.setLoadingBarStatus(75);
		buildProduct();
		buildCustomer();
		buildDelivery();
		buildEmployee();
		buildArchive();
		loadingWindow.setLoadingBarStatus(99);
		loadingWindow.closeWindow();
		panelInvoice.setVisible(true);
	}

	private void buildInvoice() {
		panelInvoice.setBackground(new Color(255, 255, 204));
		panelInvoice.setBounds(109, 82, 675, 478);
		contentPane.add(panelInvoice);
		panelInvoice.setLayout(null);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblFilter.setBounds(0, 0, 39, 17);
		panelInvoice.add(lblFilter);

		JLabel lblId = new JLabel("ID:");
		lblId.setBounds(10, 31, 22, 14);
		panelInvoice.add(lblId);

		final JTextField txtID = new JTextField();
		txtID.setBounds(33, 28, 86, 20);
		panelInvoice.add(txtID);
		txtID.setColumns(10);

		JLabel lblCustomer = new JLabel("Customer ID:");
		lblCustomer.setBounds(129, 31, 86, 14);
		panelInvoice.add(lblCustomer);

		final JTextField txtCustomerID = new JTextField();
		txtCustomerID.setBounds(200, 28, 86, 20);
		panelInvoice.add(txtCustomerID);
		txtCustomerID.setColumns(10);

		JLabel lblStatus = new JLabel("Status:");
		lblStatus.setBounds(10, 56, 46, 14);
		panelInvoice.add(lblStatus);

		final JComboBox comboBox_1 = new JComboBox();
		comboBox_1.setModel(new DefaultComboBoxModel(new String[] { "",
				"Created", "Payment pending", "Paid", "Overdue", "Canceled" }));
		comboBox_1.setBounds(10, 75, 147, 20);
		panelInvoice.add(comboBox_1);

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				salesOrders.clear();
				if (!txtID.getText().isEmpty()) {
					salesOrders.add(search.getSalesOrderById(Integer
							.parseInt(txtID.getText())));
				} else {
					if (!txtCustomerID.getText().isEmpty()) {
						if (!comboBox_1.getSelectedItem().toString().isEmpty()) {
							salesOrders = search
									.getSalesOrdersByCustomerAndStatus(Integer
											.parseInt(txtCustomerID.getText()),
											comboBox_1.getSelectedItem()
													.toString());
						} else {
							salesOrders = search
									.getSalesOrdersByCustomerId(Integer
											.parseInt(txtCustomerID.getText()));
						}
					} else {
						if (!comboBox_1.getSelectedItem().toString().isEmpty()) {
							salesOrders = search
									.getSalesOrdersByStatus(comboBox_1
											.getSelectedItem().toString());
						} else {
							salesOrders = search.getAllSalesOrders();
						}
					}
				}

				setTableInvoice(tableInvoice, salesOrders);
				((AbstractTableModel) tableInvoice.getModel())
						.fireTableDataChanged();
			}
		});
		btnSearch.setBounds(556, 74, 109, 23);
		panelInvoice.add(btnSearch);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 105, 655, 218);
		panelInvoice.add(scrollPane);

		salesOrders = search.getAllSalesOrders();
		tableInvoice.setFillsViewportHeight(true);
		setTableInvoice(tableInvoice, salesOrders);
		tableInvoice.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableInvoice.setBackground(Color.WHITE);
		scrollPane.setViewportView(tableInvoice);

		JButton btnShow = new JButton("Show details");
		btnShow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableInvoice.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableInvoice.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					detailsInvoice = new InvoiceDetails(search
							.getSalesOrderById(idSel));
					detailsInvoice.setVisible(true);
				}
			}
		});
		btnShow.setBounds(129, 334, 109, 23);
		panelInvoice.add(btnShow);

		/*
		 * JButton btnPrint = new JButton("Print");
		 * btnPrint.addActionListener(new ActionListener() { public void
		 * actionPerformed(ActionEvent e) { } }); btnPrint.setBounds(10, 334,
		 * 109, 23); panelInvoice.add(btnPrint);
		 */

		JButton btnCreateNew = new JButton("Create new");
		btnCreateNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				invoice = new Invoice();
				invoice.flushData();
				invoice.addWindowFocusListener(new WindowFocusListener() {
					@Override
					public void windowGainedFocus(WindowEvent arg0) {
						invoice.refreshLbls();
					}

					@Override
					public void windowLostFocus(WindowEvent arg0) {
					}
				});
				invoice.setVisible(true);
			}
		});
		btnCreateNew.setBounds(556, 334, 109, 23);
		panelInvoice.add(btnCreateNew);
	}

	public void refreshTableInvoice() {
		salesOrders = search.getAllSalesOrders();
		setTableInvoice(tableInvoice, salesOrders);
	}

	private void setTableInvoice(JTable jTable,
			ArrayList<SalesOrder> salesOrders) {
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "ID", "Customer", "Date",
				"Total" });
		int i = salesOrders.size();
		for (SalesOrder so : salesOrders) {
			model.addRow(new String[] {
					Integer.toString(so.getId()),
					Integer.toString(so.getCustomer().getId()),
					DateFormat.getInstance().format(so.getCreationDate())
							.substring(0, 8), Double.toString(so.getTotal()) });
		}
		jTable.setModel(model);
	}

	private void buildProduct() {
		panelProduct.setBackground(new Color(255, 255, 204));
		panelProduct.setBounds(109, 82, 675, 478);
		contentPane.add(panelProduct);
		panelProduct.setLayout(null);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblFilter.setBounds(0, 0, 39, 17);
		panelProduct.add(lblFilter);

		JLabel lblProductName = new JLabel("Name:");
		lblProductName.setBounds(129, 31, 62, 14);
		panelProduct.add(lblProductName);

		final JTextField txtProductName = new JTextField();
		txtProductName.setBounds(190, 28, 86, 20);
		panelProduct.add(txtProductName);
		txtProductName.setColumns(10);

		JLabel lblId = new JLabel("ID:");
		lblId.setBounds(10, 31, 22, 14);
		panelProduct.add(lblId);

		final JTextField txtPid = new JTextField();
		txtPid.setBounds(33, 28, 86, 20);
		panelProduct.add(txtPid);
		txtPid.setColumns(10);

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				products.clear();
				if (!txtPid.getText().isEmpty()) {
					products.add(search.getProductById(Integer.parseInt(txtPid
							.getText())));
				} else {
					if (!txtProductName.getText().isEmpty()) {
						products = search.getProductsLikeName(txtProductName
								.getText());
					} else {
						products = search.getAllProducts();
					}
				}
				setTableProduct(tableProduct, products);
				((AbstractTableModel) tableProduct.getModel())
						.fireTableDataChanged();
			}
		});
		btnSearch.setBounds(556, 74, 109, 23);
		panelProduct.add(btnSearch);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 105, 655, 218);
		panelProduct.add(scrollPane);

		tableProduct.setFillsViewportHeight(true);
		tableProduct.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableProduct.setBackground(Color.WHITE);
		scrollPane.setViewportView(tableProduct);

		JButton btnShow = new JButton("Show details");
		btnShow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableProduct.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableProduct.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					product = new GUILayer.Product(false, false, idSel);
					product.setVisible(true);
				}
			}
		});
		btnShow.setBounds(129, 334, 109, 23);
		panelProduct.add(btnShow);

		JButton btnArchive = new JButton("Archive");
		btnArchive.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int SelRowIndex = tableProduct.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableProduct.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					ModelLayer.Product product = new ModelLayer.Product();
					product = search.getProductById(idSel);
					product.setStatus("archive");
					update.updateProduct(product);
					refreshTableProduct();
				}
			}
		});
		btnArchive.setBounds(248, 334, 109, 23);
		panelProduct.add(btnArchive);

		JButton btnAddNew = new JButton("Add new");
		btnAddNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				product = new GUILayer.Product(true, false, create.getNextProductId());
				product.setVisible(true);
			}
		});
		btnAddNew.setBounds(556, 334, 109, 23);
		panelProduct.add(btnAddNew);
	}

	public void refreshTableProduct() {
		products = search.getAllProducts();
		setTableProduct(tableProduct, products);
	}

	private void setTableProduct(JTable jTable,
			ArrayList<ModelLayer.Product> products) {
		DefaultTableModel model = new DefaultTableModel();
		jTable.setModel(model);
		model.setColumnIdentifiers(new String[] { "ID", "Name", "Stock amount", "Price" });
		for (ModelLayer.Product p : products)
		{
			model.addRow(new String[] { Integer.toString(p.getId()), p.getName(), Integer.toString(p.getStockAmount()), Double.toString(p.getNettPrice()) });
		}
	}

	private void buildCustomer() {
		panelCustomer.setBackground(new Color(255, 255, 204));
		panelCustomer.setBounds(109, 82, 675, 478);
		contentPane.add(panelCustomer);
		panelCustomer.setLayout(null);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblFilter.setBounds(0, 0, 39, 17);
		panelCustomer.add(lblFilter);

		JLabel lblCustomerName = new JLabel("Name:");
		lblCustomerName.setBounds(129, 31, 62, 14);
		panelCustomer.add(lblCustomerName);

		final JTextField txtCustomerName = new JTextField();
		txtCustomerName.setBounds(190, 28, 86, 20);
		panelCustomer.add(txtCustomerName);
		txtCustomerName.setColumns(10);

		JLabel lblId = new JLabel("ID:");
		lblId.setBounds(10, 31, 22, 14);
		panelCustomer.add(lblId);

		final JTextField txtCid = new JTextField();
		txtCid.setBounds(33, 28, 86, 20);
		panelCustomer.add(txtCid);
		txtCid.setColumns(10);

		JLabel lblPayment = new JLabel("Type:");
		lblPayment.setBounds(10, 56, 109, 14);
		panelCustomer.add(lblPayment);

		final JComboBox comboPayment = new JComboBox();
		comboPayment.setModel(new DefaultComboBoxModel(new String[] { "", "Private", "Company" }));
		comboPayment.setBounds(10, 74, 109, 20);
		panelCustomer.add(comboPayment);

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				contacts.clear();
				if (!txtCid.getText().isEmpty()) {
					contacts.add(search.getCustomerById(Integer.parseInt(txtCid.getText())));
				} else {
					if (!txtCustomerName.getText().isEmpty()) {
						if (!comboPayment.getSelectedItem().toString().isEmpty()) {
							contacts = search.getCustomersByNameAndType(txtCustomerName.getText(), comboPayment.getSelectedItem().toString());
						} else {
							contacts = search.getCustomersLikeName(txtCustomerName.getText());
						}
					} else {
						if (!comboPayment.getSelectedItem().toString().isEmpty()) {
							if (comboPayment.getSelectedItem().toString().equals("Private"))
							{
								contacts = search.getAllPrivateCustomers();
							} 
							else
							{
								contacts = search.getAllBusinessCustomers();
							}
						} 
						else 
						{
							contacts = search.getAllCustomers();
						}
					}
				}
				setTableCustomer(tableCustomer, contacts);
				((AbstractTableModel) tableCustomer.getModel())
						.fireTableDataChanged();
			}
		});
		btnSearch.setBounds(556, 74, 109, 23);
		panelCustomer.add(btnSearch);

		JScrollPane scrollPaneCustomer = new JScrollPane();
		scrollPaneCustomer.setBounds(10, 105, 655, 218);
		panelCustomer.add(scrollPaneCustomer);

		tableCustomer.setFillsViewportHeight(true);
		tableCustomer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableCustomer.setBackground(Color.WHITE);
		scrollPaneCustomer.setViewportView(tableCustomer);

		JButton btnShow = new JButton("Show details");
		btnShow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableCustomer.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableCustomer.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					Contact c = search.getCustomerById(idSel);
					boolean isPrivate = false;
					if (c instanceof Private) {
						isPrivate = true;
					}
					customerD = new GUILayer.CustomerDetails(idSel, isPrivate,
							false);
					customerD.setVisible(true);
				}
			}
		});
		btnShow.setBounds(129, 334, 109, 23);
		panelCustomer.add(btnShow);

		JButton btnArchive = new JButton("Archive");
		btnArchive.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableCustomer.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} 
				else 
				{
					String idSelected = (String) tableCustomer.getValueAt(SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					ModelLayer.Contact customer = new ModelLayer.Contact();
					customer = search.getCustomerById(idSel);
					customer.setStatus("archive");
					update.updateCustomer(customer);
					contacts.clear();
					contacts = search.getAllCustomers();
					setTableCustomer(tableCustomer, contacts);
				}
			}
		});
		btnArchive.setBounds(248, 334, 109, 23);
		panelCustomer.add(btnArchive);

		JButton btnAddNew = new JButton("Add new");
		btnAddNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				customerN = new NewCustomer();
				customerN.setVisible(true);
			}
		});
		btnAddNew.setBounds(556, 334, 109, 23);
		panelCustomer.add(btnAddNew);
	}

	public void refreshTableCustomer() {
		contacts = search.getAllCustomers();
		setTableCustomer(tableCustomer, contacts);
	}

	private void setTableCustomer(JTable jTable,
			ArrayList<ModelLayer.Contact> contacts) {
		DefaultTableModel model = new DefaultTableModel();
		jTable.setModel(model);
		model.setColumnIdentifiers(new String[] { "ID", "Name", "Type",
				"Address", "E-mail", "Phone" });
		String name = "";
		String type = "";
		for (Contact c : contacts) {
			if (c instanceof Private) {
				Private p = (Private) c;
				name = p.getName() + " " + p.getSurname();
				type = "private";
			} else {
				Business b = (Business) c;
				name = b.getName();
				type = "company";
			}
			model.addRow(new String[] { Integer.toString(c.getId()), name,
					type, c.getAddress(), c.getEMail(), c.getPhoneNO() });
		}
	}

	private void buildDelivery() {
		panelDelivery.setBackground(new Color(255, 255, 204));
		panelDelivery.setBounds(109, 82, 675, 478);
		contentPane.add(panelDelivery);
		panelDelivery.setLayout(null);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblFilter.setBounds(0, 0, 39, 17);
		panelDelivery.add(lblFilter);

		JLabel lblId = new JLabel("ID:");
		lblId.setBounds(10, 31, 22, 14);
		panelDelivery.add(lblId);

		final JTextField txtDid = new JTextField();
		txtDid.setBounds(33, 28, 86, 20);
		panelDelivery.add(txtDid);
		txtDid.setColumns(10);

		JLabel lblStatus = new JLabel("Status:");
		lblStatus.setBounds(10, 56, 109, 14);
		panelDelivery.add(lblStatus);

		final JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "",
				"Created", "In progress", "Delivered", "Canceled" }));
		comboBox.setBounds(10, 74, 109, 20);
		panelDelivery.add(comboBox);

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				deliveries.clear();
				if (!txtDid.getText().isEmpty()) {
					deliveries.add(search.getDeliveryById(Integer
							.parseInt(txtDid.getText())));

				} else {
					if (!comboBox.getSelectedItem().toString().isEmpty()) {
						deliveries = search.getDeliveriesByStatus(comboBox
								.getSelectedItem().toString());
					} else {
						deliveries = search.getAllDelivery();
					}
				}
				setTableDelivery(tableDelivery, deliveries);
				((AbstractTableModel) tableDelivery.getModel())
						.fireTableDataChanged();
			}
		});
		btnSearch.setBounds(556, 74, 109, 23);
		panelDelivery.add(btnSearch);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 105, 655, 218);
		panelDelivery.add(scrollPane);

		tableDelivery.setFillsViewportHeight(true);
		tableDelivery.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableDelivery.setBackground(Color.WHITE);
		scrollPane.setViewportView(tableDelivery);

		JButton btnShow = new JButton("Show details");
		btnShow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableDelivery.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableDelivery.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					delivery = new Delivery(false, idSel);
					delivery.setVisible(true);
				}
			}
		});
		btnShow.setBounds(129, 334, 109, 23);
		panelDelivery.add(btnShow);

		final int nextIndex = create.getNextDeliveryId();
		JButton btnCreateNew = new JButton("Create new");
		btnCreateNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				delivery = new Delivery(true, nextIndex);
				delivery.setVisible(true);
			}
		});
		btnCreateNew.setBounds(556, 334, 109, 23);
		panelDelivery.add(btnCreateNew);

	}

	public void refreshTableDelivery() {
		deliveries = search.getAllDelivery();
		setTableDelivery(tableDelivery, deliveries);
	}

	private void setTableDelivery(JTable jTable,
			ArrayList<ModelLayer.Delivery> deliveries) {
		DefaultTableModel model = new DefaultTableModel();
		model.setColumnIdentifiers(new String[] { "ID", "Date", "Status" });
		for (ModelLayer.Delivery d : deliveries) {
			model.addRow(new String[] {
					Integer.toString(d.getDeliveryId()),
					DateFormat.getInstance().format(d.getDeliveryDate())
							.substring(0, 8), d.getDeliveryState() });
		}
		jTable.setModel(model);
	}

	private void buildEmployee() {
		panelEmployee.setBackground(new Color(255, 255, 204));
		panelEmployee.setBounds(109, 82, 675, 478);
		contentPane.add(panelEmployee);
		panelEmployee.setLayout(null);

		JLabel lblFilter = new JLabel("Filter:");
		lblFilter.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblFilter.setBounds(0, 0, 39, 17);
		panelEmployee.add(lblFilter);

		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(129, 31, 62, 14);
		panelEmployee.add(lblName);

		final JTextField txtName = new JTextField();
		txtName.setBounds(190, 28, 86, 20);
		panelEmployee.add(txtName);
		txtName.setColumns(10);

		JLabel lblId = new JLabel("ID:");
		lblId.setBounds(10, 31, 22, 14);
		panelEmployee.add(lblId);

		final JTextField txtEid = new JTextField();
		txtEid.setBounds(33, 28, 86, 20);
		panelEmployee.add(txtEid);
		txtEid.setColumns(10);

		JLabel lblPayment = new JLabel("Role:");
		lblPayment.setBounds(10, 56, 109, 14);
		panelEmployee.add(lblPayment);

		final JComboBox comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] { "",
				"Manager", "Warehouse", "Office", "Delivery" }));
		comboBox.setBounds(10, 74, 109, 20);
		panelEmployee.add(comboBox);

		JButton btnSearch = new JButton("Search");
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				employees.clear();
				if (!txtEid.getText().isEmpty()) {
					employees.add(search.getEmployeeById(Integer
							.parseInt(txtEid.getText())));
				} else {
					if (!txtName.getText().isEmpty()) {
						if (!comboBox.getSelectedItem().toString().isEmpty()) {
							employees = search.getEmployeeByNameAndRole(txtName
									.getText(), comboBox.getSelectedItem()
									.toString());
						} else {
							employees = search.getEmployeesLikeName(txtName
									.getText());
						}
					} else {
						if (!comboBox.getSelectedItem().toString().isEmpty()) {
							employees = search.getEmployeesByRole(comboBox
									.getSelectedItem().toString());
						} else {
							employees = search.getAllEmployees();
						}
					}
				}

				setTableEmployee(tableEmployee, employees);
				((AbstractTableModel) tableEmployee.getModel())
						.fireTableDataChanged();
			}
		});
		btnSearch.setBounds(556, 74, 109, 23);
		panelEmployee.add(btnSearch);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 105, 655, 218);
		panelEmployee.add(scrollPane);

		tableEmployee.setFillsViewportHeight(true);
		tableEmployee.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableEmployee.setBackground(Color.WHITE);
		scrollPane.setViewportView(tableEmployee);

		JButton btnShow = new JButton("Show details");
		btnShow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableEmployee.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableEmployee.getValueAt(
							SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					employee = new GUILayer.Employee(false, false, idSel);
					employee.setVisible(true);
				}
			}
		});
		btnShow.setBounds(129, 334, 109, 23);
		panelEmployee.add(btnShow);

		JButton btnArchive = new JButton("Archive");
		btnArchive.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int SelRowIndex = tableEmployee.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				} else {
					String idSelected = (String) tableEmployee.getValueAt(SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					ModelLayer.Employee employee = new ModelLayer.Employee();
					employee = search.getEmployeeById(idSel);
					employee.setStatus("archive");
					update.updateEmployee(employee);
					refreshTableEmployee();
				}
			}
		});
		btnArchive.setBounds(248, 334, 109, 23);
		panelEmployee.add(btnArchive);

		final int id = create.getNextContactId();
		JButton btnCreateNew = new JButton("Create new");
		btnCreateNew.setBounds(556, 334, 109, 23);
		btnCreateNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				employee = new GUILayer.Employee(true, false, id);
				employee.setVisible(true);
			}
		});
		panelEmployee.add(btnCreateNew);
	}

	public void refreshTableEmployee() {
		employees = search.getAllEmployees();
		setTableEmployee(tableEmployee, employees);
	}

	private void setTableEmployee(JTable jTable, ArrayList<ModelLayer.Employee> employees) {
		DefaultTableModel model = new DefaultTableModel();
		jTable.setModel(model);
		model.setColumnIdentifiers(new String[] { "ID", "Name", "Address", "E-mail", "Telephone", "Role", "Salary" });
		for (ModelLayer.Employee e : employees) {
			String name = e.getName() + " " + e.getSurname();
			model.addRow(new String[] { Integer.toString(e.getId()), name,
					e.getAddress(), e.getEMail(), e.getPhoneNO(), e.getRole(),
					Double.toString(e.getSalaryPerHour()) });
		}
	}

	private void buildStats() {
		
		loadingWindow.setLoadingBarStatus(1);
		
		panelStats.setBackground(new Color(255, 255, 204));
		panelStats.setBounds(109, 82, 675, 478);
		contentPane.add(panelStats);
		panelStats.setLayout(null);

		String employeeName = search.getMostProductiveEmployee().getName();
		String employeeId = Integer.toString(search.getMostProductiveEmployee().getId());
		JLabel lblEmployee = new JLabel("The most productive employee is: " + employeeName + " (ID: " + employeeId + ").");
		lblEmployee.setBounds(10, 10, 670, 30);
		panelStats.add(lblEmployee);
		
		loadingWindow.setLoadingBarStatus(33);
		
		String name = "";
		Contact contact = search.getBestCustomer();
		if (contact instanceof Private) {
			Private p = (Private) contact;
			name = p.getName();
		} else {
			Business b = (Business) contact;
			name = b.getName();
		}
		String id = Integer.toString(search.getBestCustomer().getId());
		JLabel lblBestCustomer = new JLabel("The best customer is: " + name + " (ID: " + id + ").");
		lblBestCustomer.setBounds(10, 50, 670, 30);
		panelStats.add(lblBestCustomer);

		loadingWindow.setLoadingBarStatus(66);
		
		String mostProductName = search.getMostSoldProduct().getName();
		String mostProductId = Integer.toString(search.getMostSoldProduct().getId());
		JLabel lblMostProduct = new JLabel("The most sold product is: " + mostProductName + " (ID: " + mostProductId + ").");
		lblMostProduct.setBounds(10, 90, 670, 30);
		panelStats.add(lblMostProduct);

		loadingWindow.setLoadingBarStatus(99);
		
		// JButton btnStockCheck = new JButton("Check stock");
		// btnStockCheck.addActionListener(new ActionListener() {
		// public void actionPerformed(ActionEvent e) {
		//
		// }
		// });
		// btnStockCheck.setBounds(10, 150, 109, 30);
		// panelStats.add(btnStockCheck);

	}

	private void buildArchive() {
		panelArchive.setBackground(new Color(255, 255, 204));
		panelArchive.setBounds(109, 82, 675, 478);
		contentPane.add(panelArchive);
		panelArchive.setLayout(null);

		JLabel lblContact = new JLabel("Archive contacts:");
		lblContact.setBounds(15, 10, 250, 20);
		lblContact.setFont(new Font("Tahoma", Font.PLAIN, 14));
		panelArchive.add(lblContact);

		JLabel lblProduct = new JLabel("Archived products:");
		lblProduct.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblProduct.setBounds(360, 10, 250, 20);
		panelArchive.add(lblProduct);

		final JTextField txtCName = new JTextField();
		txtCName.setBounds(15, 40, 150, 20);
		panelArchive.add(txtCName);

		JButton btnSearchAC = new JButton("Search");
		btnSearchAC.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				archivedContacts.clear();
				if (!txtCName.getText().isEmpty()) {
					archivedContacts = search
							.getAllArchivedContactsLikeName(txtCName.getText());
				} else {
					archivedContacts = search.getAllArchivedContacts();
				}
				setTableArchiveContacts(tableArchiveContact, archivedContacts);
				((AbstractTableModel) tableArchiveContact.getModel()).fireTableDataChanged();
			}
		});
		btnSearchAC.setBounds(191, 37, 109, 23);
		panelArchive.add(btnSearchAC);

		final JTextField txtPName = new JTextField();
		txtPName.setBounds(360, 40, 150, 20);
		panelArchive.add(txtPName);

		JButton btnSearchAP = new JButton("Search");
		btnSearchAP.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				archivedProducts.clear();
				if (!txtCName.getText().isEmpty()) {
					archivedProducts = search
							.getArchivedProductsLikeName(txtPName.getText());
				} else {
					archivedProducts = search.getArchivedProducts();
				}
				setTableArchiveProducts(tableArchiveProduct, archivedProducts);
				((AbstractTableModel) tableArchiveContact.getModel()).fireTableDataChanged();
			}
		});
		btnSearchAP.setBounds(536, 37, 109, 23);
		panelArchive.add(btnSearchAP);

		JScrollPane scrollPaneContact = new JScrollPane();
		scrollPaneContact.setBounds(10, 70, 300, 200);
		panelArchive.add(scrollPaneContact);

		tableArchiveContact.setFillsViewportHeight(true);
		tableArchiveContact.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableArchiveContact.setBackground(Color.WHITE);
		scrollPaneContact.setViewportView(tableArchiveContact);

		JScrollPane scrollPaneProduct = new JScrollPane();
		scrollPaneProduct.setBounds(360, 70, 300, 200);
		panelArchive.add(scrollPaneProduct);

		tableArchiveProduct.setFillsViewportHeight(true);
		tableArchiveProduct.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableArchiveProduct.setBackground(Color.WHITE);
		scrollPaneProduct.setViewportView(tableArchiveProduct);
		
		JButton detailsC = new JButton("Details");
		detailsC.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0){
				int SelRowIndex = tableArchiveContact.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				}
				else
				{
					String idSelected = (String) tableArchiveContact.getValueAt(SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);
					String type = (String) tableArchiveContact.getValueAt(SelRowIndex, 2);
					if(type.equals("employee"))
					{
						GUILayer.Employee emp = new GUILayer.Employee(false, true, idSel);
						emp.setVisible(true);
					}
					else
					{
						Contact c = search.getCustomerById(idSel);
						boolean isPrivate = false;
						if (c instanceof Private)
						{
							isPrivate = true;
						}
						customerD = new GUILayer.CustomerDetails(idSel, isPrivate,true);
						customerD.setVisible(true);
					}
				}
			}
		});
		detailsC.setBounds(30, 280, 250, 20);
		panelArchive.add(detailsC);
		
		JButton detailsP = new JButton("Details");
		detailsP.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0){
				int SelRowIndex = tableArchiveProduct.getSelectedRow();
				if (SelRowIndex == -1) {
					JOptionPane.showMessageDialog(null,
							"You have to chose one from the list", "Warning",
							JOptionPane.WARNING_MESSAGE);
				}
				else
				{
					String idSelected = (String) tableArchiveProduct.getValueAt(SelRowIndex, 0);
					int idSel = Integer.parseInt(idSelected);					
					ModelLayer.Product p = search.getProductById(idSel);
					GUILayer.Product productWindow = new GUILayer.Product(false, true, idSel);
					productWindow.setVisible(true);
					
				}
			}
		});
		detailsP.setBounds(390, 280, 250, 20);
		panelArchive.add(detailsP);
		

		panelArchive.setVisible(false);
	}

	private void setTableArchiveContacts(JTable tableAContact, ArrayList<Contact> archivedContacts) {
		DefaultTableModel model = new DefaultTableModel();
		tableAContact.setModel(model);
		model.setColumnIdentifiers(new String[] { "ID", "Name", "Type" });

		String name = "";
		String type = "";
		for (ModelLayer.Contact c : archivedContacts) {
			if (c instanceof Private) {
				Private p = (Private) c;
				name = p.getName() + " " + p.getSurname();
				type = "private";
			} else {
				if (c instanceof Business) {
					Business b = (Business) c;
					name = b.getName();
					type = "company";
				} else {
					Employee e = (Employee) c;
					name = e.getName() + " " + e.getSurname();
					type = "employee";
				}
			}
			model.addRow(new String[] { Integer.toString(c.getId()), name, type });
		}
	}
	
	public void refreshAC()
	{
		archivedContacts.clear();
		archivedContacts = search.getAllArchivedContacts();
		setTableArchiveContacts(tableArchiveContact, archivedContacts);
	}

	private void setTableArchiveProducts(JTable tableAProduct, ArrayList<ModelLayer.Product> archivedProducts) {
		DefaultTableModel model = new DefaultTableModel();
		tableAProduct.setModel(model);
		model.setColumnIdentifiers(new String[] {"ID", "Name"});
		for(ModelLayer.Product p : archivedProducts)
		{
			model.addRow(new String[] {Integer.toString(p.getId()), p.getName()});
		}

	}
	
	public void refreshAP()
	{
		archivedProducts.clear();
		archivedProducts = search.getArchivedProducts();
		setTableArchiveProducts(tableArchiveProduct, archivedProducts);
	}
	
	class Statistics extends SwingWorker<Void, Void> {

        @Override
        protected Void doInBackground() throws Exception {
        		loadingWindow.showWindow();
                buildStats();
                panelStats.setVisible(false);
                panelStats.setVisible(true);
                loadingWindow.closeWindow();
                return null;
        }
}

}
